package com.vxfly.helioscamera.function;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.vxfly.helioscamera.log.WriteLogToDevice;
import com.icatch.wificam.customer.ICatchWificamMediaServer;
import com.icatch.wificam.customer.type.ICatchCodec;
import com.icatch.wificam.customer.type.ICatchFrameBuffer;

public class AudioRecordingThread extends Thread {
	private static final int sample_rate = 44100;
	private static final int sample_chnl = AudioFormat.CHANNEL_IN_STEREO;
	private static final int sample_bits = AudioFormat.ENCODING_PCM_16BIT;

	private boolean thread_running = false;
	private AudioRecord record;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		// photo capture
		WriteLogToDevice.writeLog("[Normal] -- AudioRecordingThread: ", "start AudioRecordingThread");
		ICatchWificamMediaServer.getInstance().startMediaServer(false, ICatchCodec.ICH_CODEC_JPEG, true, ICatchCodec.ICH_CODEC_PCM,
				sample_bits, sample_rate, sample_chnl);
		thread_running = true;

		int bufferSize = AudioRecord.getMinBufferSize(sample_rate, sample_chnl, sample_bits);
		record = new AudioRecord(MediaRecorder.AudioSource.MIC, sample_rate, sample_chnl, sample_bits, bufferSize);

		byte[] buffer = new byte[bufferSize];
		ICatchFrameBuffer frame = new ICatchFrameBuffer(buffer);

		record.startRecording();
		long start_tm = System.currentTimeMillis();

		while (thread_running) {
			int frameSize = record.read(buffer, 0, buffer.length);
			if (frameSize <= 0) {
				continue;
			}

			frame.setFrameSize(frameSize);
			frame.setPresentationTime(System.currentTimeMillis() - start_tm);
			ICatchWificamMediaServer.getInstance().writeAudioFrame(frame);
		}
	}

	public void stopThread() {
		thread_running = false;
		ICatchWificamMediaServer.getInstance().closeMediaServer();
		record.stop();
	}
}